import React, { 
  useCallback, 
  useRef, 
  forwardRef,
  useImperativeHandle,
  useState
} from 'react'

const Input = forwardRef((props, ref) => {
  const childRef = useRef(null)
  const [msg, setMsg] = useState('hello')

  useImperativeHandle(ref, () => {
    return {
      focus: () => {
        childRef.current.focus()
      },
      setMessage: (args) => {
        setMsg(args)
      }
    }
  })

  return (
    <>
      <div>{msg}</div>
      <input ref={childRef} type="text" />
    </>
  )
})

export default function UseImperativeHandleDemo2() {

  const parentsRef = useRef(null)

  const handleClick = useCallback(() => {
    parentsRef.current.focus()
    parentsRef.current.setMessage('world')
  }, [])

  return (
    <>
      <Input ref={parentsRef}></Input>
      <button onClick={handleClick}>focus</button>
    </>
  )
}
